package se.chalmers.tda366.crumble.downloader.impl;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;

import se.chalmers.tda366.crumble.core.IArticle;
import se.chalmers.tda366.crumble.core.IFeed;
import se.chalmers.tda366.crumble.core.impl.Article;
import se.chalmers.tda366.crumble.downloader.IDownloader;

import com.sun.cnpi.rss.elements.Item;
import com.sun.cnpi.rss.elements.Rss;
import com.sun.cnpi.rss.parser.RssParser;
import com.sun.cnpi.rss.parser.RssParserException;
import com.sun.cnpi.rss.parser.RssParserFactory;

public class Downloader implements IDownloader {

	private URL url;
	private RssParser parser;
	private Rss rss;
	
	// Downloader takes a feed and creates its parser	
	public Downloader(IFeed feed) {
		try {
			url = new URL(feed.getSource());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		rss = null;
		try{
			parser=RssParserFactory.createDefault();
		} catch(RssParserException rpe){
			rpe.printStackTrace();
		}
	}

	// Returns the new list of articles in the feed
	@Override
	public ArrayList<IArticle> getFeed() {
		ArrayList<IArticle> articles = new ArrayList<IArticle>();
		IFeed feed = null;
		try {
			rss=parser.parse(url);
		} catch (RssParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (rss != null) {
			Collection rssRawItems = rss.getChannel().getItems(); 
			ArrayList<Item> rssItems = new ArrayList(rssRawItems);
			for(Item item : rssItems) {
				IArticle newArt = new Article(item);
				articles.add(newArt);
			}
		}
		
		return articles;
	}
	
}
